package org.ddevil.data;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;

import javax.swing.text.DateFormatter;

import org.ddevil.data.util.DataUtils;


/**
 * 
 * This class provides a comparator for dates. The developer may specify a date
 * format but any dates which do not meet the format will be set to null for
 * comparison purposes. This comparator deals with nulls as null == null, null <
 * !null.
 * 
 * <table width = 100% border=1>
 * <tr>
 * <td colspan="3" align="center"><strong>History</strong></td>
 * </tr>
 * <tr>
 * <th>Date</th>
 * <th>Name</th>
 * <th>Desc</th>
 * </tr>
 * </table>
 * 
 * @author Eric Lundin
 * 
 */
public class DateComparator implements Comparator {
	/** The default date format */
	public static final String DEFAULT_FORMAT = "MM/dd/yyyy";

	/** The date formatter we will use */
	DateFormatter formatter;

	/** The date format our dates will follow */
	SimpleDateFormat format;

	/**
	 * Creates a comparator using the default M&SWP date format of MM/dd/YYYY.
	 */
	public DateComparator() {
		this(DEFAULT_FORMAT);
	}

	/**
	 * Construct a comparator for a custom date format. Valid Patterns:
	 * <UL>
	 * <LI>y Year</LI>
	 * <LI>M Month in year</LI>
	 * <LI>W Week in month</LI>
	 * <LI>D Day in year</LI>
	 * <LI>d Day in month </LI>
	 * <LI>E Day in week </LI>
	 * <LI>a Am/pm marker </LI>
	 * <LI>H Hour in day </LI>
	 * <LI>k Hour in day (1-24)</LI>
	 * <LI>K Hour in am/pm (0-11)</LI>
	 * <LI>h Hour in am/pm (1-12)</LI>
	 * <LI>m Minute in hour </LI>
	 * <LI>s Second in minute</LI>
	 * </UL>
	 * 
	 * @param dateFormat
	 *            The date format to use.
	 * 
	 * @throws IllegalArgumentException
	 *             If the format String is invalid.
	 * 
	 */
	public DateComparator(String dateFormat) {
		super();
		format = new SimpleDateFormat(dateFormat);
		formatter = new DateFormatter(format);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.util.Comparator#compare(T, T)
	 */
	public int compare(Object o1, Object o2) {
		String string1 = (o1 != null ? o1.toString() : null);
		String string2 = (o2 != null ? o2.toString() : null);
		Date date1 = null;
		Date date2 = null;
		int retVal;

        if(DataUtils.hasValue(string1)){
    		try {
    			date1 = (Date) formatter.stringToValue(string1);
    		} catch (ParseException pe) {                
    		}
        }
        if(DataUtils.hasValue(string2)){
    		try {
    			date2 = (Date) formatter.stringToValue(string2);
    		} catch (ParseException pe) {                
    		}
        }

		if (date1 == null && date2 != null) {
			retVal = -1;
		} else if (date1 != null && date2 == null) {
			retVal = 1;
		} else if (date1 == null && date2 == null) {
			retVal = 0;
		} else {
			retVal = date1.compareTo(date2);
		}
		return retVal;
	}
}
